package binarytree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/21 1:17
 * https://leetcode-cn.com/problems/find-bottom-left-tree-value/
 * 给定一个二叉树的 根节点 root，请找出该二叉树的 最底层 最左边 节点的值。
 */
public class FindBottomLeftValue {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 迭代 层次遍历
     * @param root
     * @return
     */
    public static int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> stack = new LinkedList<>();
        TreeNode leftNode = null;
        stack.offer(root);
        while (!stack.isEmpty()) {
            int size= stack.size();
            leftNode = stack.peek();
            for (int i = 0; i < size; i++) {
                TreeNode pop = stack.poll();
                if (pop.left != null) {
                    stack.offer(pop.left);
                }
                if (pop.right != null) {
                    stack.offer(pop.right);
                }
            }
        }
        return leftNode.val;
    }

    private static int maxDepth = 0, value=0;

    /**
     * 递归遍历
     * @param root
     * @return
     */
    public int findBottomLeftValue1(TreeNode root) {
        int depth = 0;
        getLeftLeaf(root, depth);
        return value;
    }

    public void getLeftLeaf(TreeNode root, int depth) {
        if (root.left == null && root.right == null) {
            //先递归左边，再出现深度相等的节点直接忽略
            if (depth > maxDepth) {
                maxDepth = depth;
                value = root.val;
            }
            return;
        }
        if (root.left != null) {
            getLeftLeaf(root.left, depth + 1);
        }
        if (root.right != null) {
            getLeftLeaf(root.right, depth + 1);
        }
    }



    public static void main(String[] args) {
        TreeNode root = new TreeNode(2);
        TreeNode left = new TreeNode(1);
        TreeNode right = new TreeNode(3);
        root.left = left;
        root.right = right;
        int bottomLeftValue = findBottomLeftValue(root);
        System.out.println();
    }
}
